package top.kaoshanji.p2ch15b;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 代码清单-p2ch15b-453页a：生产者/消费者协作队列
 * author kaoshanji
 * ^_^
 * create time 2025/2/24 16:01
 */
public class MyBlockingQueue<E> {

    private Queue<E> queue = null;
    private int limit; // 队列元素的上限

    public MyBlockingQueue(int limit) {
        this.limit = limit;
        this.queue = new ArrayDeque<>(limit);
    }

    // 添加元素
    public synchronized void put(E e) throws InterruptedException {
        // 如果满了，就需要等待
        while (queue.size() == limit) {
            wait();
        }

        queue.add(e);
        notifyAll();
    }

    // 获取队首元素
    public synchronized E take() throws InterruptedException {
        // 如果是空的，就需要等待
        while (queue.isEmpty()) {
            wait();
        }

        E e = queue.poll();
        notifyAll();
        return e;
    }

}
